﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace Extensions
{
    /// <summary>
    /// 属性扩展方法
    /// </summary>
    public static class AttributeExtensions
    {
        /// <summary>
        /// 获取成员信息的 Description
        /// </summary>
        /// <param name="mi">成员信息</param>
        /// <returns>Description</returns>
        public static string GetDescription(this MemberInfo mi)
        {
            return mi.FirstAttribute<DescriptionAttribute>()?.Description;
        }

        public static TAttribute FirstAttribute<TAttribute>(this MemberInfo memberInfo)
        {
            return memberInfo.AllAttributes<TAttribute>().FirstOrDefault();
        }

        public static TAttribute FirstAttribute<TAttribute>(this PropertyInfo propertyInfo)
        {
            return propertyInfo.AllAttributes<TAttribute>().FirstOrDefault();
        }

        public static TAttr[] AllAttributes<TAttr>(this MemberInfo mi)
        {
            return mi.AllAttributes(typeof(TAttr)).Cast<TAttr>().ToArray();
        }

        public static object[] AllAttributes(this MemberInfo memberInfo, Type attrType)
        {
            PropertyInfo propertyInfo = memberInfo as PropertyInfo;
            if (!(propertyInfo != null))
            {
                return memberInfo.GetCustomAttributes(attrType, inherit: true);
            }
            return propertyInfo.AllAttributes(attrType);
        }
    }
}